package member_coupon

import (
	// "bp/cache"
	sqlc "bp/db/sqlc"
	"bp/internal/util"
	"context"
	"fmt"
)

// CreateCoupon 新建优惠券参数
type CreateMemberCouponParam struct {
	CreateMemberCouponParamsPtr *sqlc.CreateMemberCouponParams
}

// CreateMemberCoupon 新建会员优惠券
func (s *MemberCouponEntityServiceImp) CreateMemberCoupon(ctx context.Context, q *sqlc.Queries, ptr *CreateMemberCouponParam) (
	memberCouponPtr *sqlc.MemberCoupon,
	err error) {
	slog := util.NewContextLogger(ctx, s.slog)

	memberCoupon, err := q.CreateMemberCoupon(ctx, *ptr.CreateMemberCouponParamsPtr)
	if err != nil {
		return
	}
	slog.Infof("1 CreateMemberCoupon ok")

	memberCouponPtr = &memberCoupon
	return
}

func (s *MemberCouponEntityServiceImp) FreezeMemberCoupons(ctx context.Context, q *sqlc.Queries, ptr *sqlc.FreezeMemberCouponsParams) (err error) {
	err = q.FreezeMemberCoupons(ctx, *ptr)
	if err != nil {
		return
	}
	return
}


func (s *MemberCouponEntityServiceImp) NormalizeMemberCouponsByOutTransNo(ctx context.Context, q *sqlc.Queries, outTransNo string) (err error) {
	if util.IsEmpty(outTransNo) {
		return fmt.Errorf("ApplyMemberCoupons 无效的参数outTransNo(%s)", outTransNo)
	}
	err = q.NormalizeMemberCouponsByOutTransNo(ctx, sqlc.NSFromString(outTransNo))
	if err != nil {
		return
	}
	return
}

func (s *MemberCouponEntityServiceImp) NormalizeMemberCouponsByOutTransNoAndOutOrderNo(ctx context.Context, q *sqlc.Queries, outTransNo, outOrderNo string) (err error) {
	if util.IsEmpty(outTransNo) {
		return fmt.Errorf("ApplyMemberCoupons 无效的参数outTransNo(%s)", outTransNo)
	}
	if util.IsEmpty(outOrderNo) {
		return fmt.Errorf("ApplyMemberCoupons 无效的参数outOrderNo(%s)", outOrderNo)
	}
	err = q.NormalizeMemberCouponsByOutTransNoAndOutOrderNo(ctx, sqlc.NormalizeMemberCouponsByOutTransNoAndOutOrderNoParams{
		OutTransNo: sqlc.NSFromString(outTransNo),
		OutOrderNo: sqlc.NSFromString(outOrderNo),
	})
	if err != nil {
		return
	}
	return
}

func (s *MemberCouponEntityServiceImp) ApplyMemberCoupons(ctx context.Context, q *sqlc.Queries, outTransNo string) (err error) {
	if util.IsEmpty(outTransNo) {
		return fmt.Errorf("ApplyMemberCoupons 无效的参数outTransNo(%s)", outTransNo)
	}
	err = q.ApplyMemberCouponsByOutTransNo(ctx, sqlc.NSFromString(outTransNo))
	if err != nil {
		return
	}
	return
}

// ExpireMemberCoupons 过期会员优惠券
func (s *MemberCouponEntityServiceImp) ExpireMemberCoupons(ctx context.Context, q *sqlc.Queries, limit int32) (err error) {
	slog := util.NewContextLogger(ctx, s.slog)

	cnt, err := q.BatchFinishOrCloseMemberCoupon(ctx, limit)
	if err != nil {
		return
	}
	slog.Infof("BatchFinishOrCloseMemberCoupon (%d)条", cnt)

	return
}